<?php


namespace app\home\services;

use app\admin\model\StoreModel;

class StoreService
{
    private $model;

    public function __construct()
    {
        $this->model = new StoreModel();
    }

    /**
     * 新增或修改
     * @param $id
     * @param $data
     */
    public function save($id, $data)
    {
        if ($id) {
            $info = $this->getInfoByTitle($data['title']);
            if (!empty($info)) {
                if ($info['id'] != $id) {
                    return [-1, '店铺名已存在'];
                }
            }
            $res = $this->model->save($data, ['id' => $id]);
            if ($res) {
                return [0, '修改成功', $id];
            } else {
                return [-1, '修改失败', $id];
            }
        } else {
            $info = $this->getInfoByTitle($data['title']);
            if (!empty($info)) {
                return [-1, '店铺名已存在'];
            }
            $data['create_time'] = time();
            $res = $this->model->save($data);
            if ($res) {
                return [0, '新增成功', $this->model->id];
            } else {
                return [-1, '新增失败', 0];
            }
        }
    }

    public function getInfoById($id, $field = [])
    {
        if ($id == "") {
            return [];
        }
        $info = $this->model->where([
            'id' => $id
        ])->field($field)->find();
        return $info ?: [];
    }

    public function getInfoByTitle($title)
    {
        if ($title == "") {
            return [];
        }
        $info = $this->model->where([
            'title' => $title
        ])->find();
        return $info;
    }

    public function getListByWhere($param = [], $field = [])
    {
        $where = [];
        if (!isset($param['page']) || (int)$param['page'] <= 1) {
            $param['page'] = 1;
        }
        if (!isset($param['pageSize']) || (int)$param['pageSize'] <= 0) {
            $param['pageSize'] = 5;
        }
        if ($param['province_id']) {
            $where[] = ['province_id', '=', $param['province_id']];
        }
        if ($param['city_id']) {
            $where[] = ['city_id', '=', $param['city_id']];
        }
        if ($param['title']) {
            $where[] = ['title', 'like', "%{$param['title']}%"];
        }
        $list = $this->model->field($field)->where($where)->limit(($param['page'] - 1) * $param['pageSize'], $param['pageSize'])->select();
        return $list;
    }
}